import { Command } from 'commander';
import inquirer from 'inquirer';
import { config } from '../services/config';
import { logger } from '../utils/logger';
import { createTable } from '../utils/table';
import { CLIError } from '../types';

export function configCommands(program: Command): void {
  const configCmd = program
    .command('config')
    .description('CLI configuration management');

  configCmd
    .command('list')
    .description('Show current configuration')
    .action(async () => {
      try {
        const allConfig = config.getAll();
        
        logger.log('\nCurrent Configuration:');
        logger.log(`API URL: ${allConfig.apiUrl}`);
        logger.log(`Current Project: ${allConfig.currentProject || 'None'}`);
        logger.log(`Current Environment: ${allConfig.currentEnvironment || 'dev'}`);
        logger.log(`Authenticated: ${allConfig.token ? 'Yes' : 'No'}`);
        
        if (allConfig.token) {
          logger.log(`Token: ${allConfig.token.substring(0, 10)}...`);
        }
      } catch (error) {
        throw new CLIError('Failed to display configuration');
      }
    });

  configCmd
    .command('set <keyValue>')
    .description('Set a configuration value (format: KEY=VALUE)')
    .action(async (keyValue: string) => {
      try {
        if (!keyValue.includes('=')) {
          throw new CLIError('Invalid format. Use: cm config set KEY=VALUE');
        }

        const [key, ...valueParts] = keyValue.split('=');
        const value = valueParts.join('=');

        if (!key || !value) {
          throw new CLIError('Both key and value are required');
        }

        const validKeys = ['apiUrl', 'currentProject', 'currentEnvironment'];
        
        if (!validKeys.includes(key)) {
          throw new CLIError(`Invalid configuration key. Valid keys: ${validKeys.join(', ')}`);
        }

        if (key === 'apiUrl' && !value.startsWith('http')) {
          throw new CLIError('API URL must start with http:// or https://');
        }

        config.set(key as any, value);
        logger.success(`Configuration updated: ${key} = ${value}`);
      } catch (error) {
        if (error instanceof CLIError) {
          throw error;
        }
        throw new CLIError('Failed to set configuration');
      }
    });

  configCmd
    .command('reset')
    .description('Reset configuration to defaults')
    .action(async () => {
      try {
        const confirm = await inquirer.prompt([
          {
            type: 'confirm',
            name: 'reset',
            message: 'This will clear all configuration including authentication. Continue?',
            default: false
          }
        ]);

        if (!confirm.reset) {
          logger.info('Reset cancelled');
          return;
        }

        config.clear();
        logger.success('Configuration reset to defaults');
        logger.info('You will need to login again with "cm login"');
      } catch (error) {
        throw new CLIError('Failed to reset configuration');
      }
    });

  program
    .command('help [command]')
    .description('Show help information')
    .action(async (command?: string) => {
      if (command) {
        program.outputHelp();
        return;
      }

      logger.log(`
CModel CLI - Cloud Module Management Tool
`);
      
      const sections = [
        {
          title: '🔑 Authentication & Project',
          commands: [
            ['cm login', 'Login to the platform'],
            ['cm logout', 'Logout from the platform'],
            ['cm whoami', 'Display current user'],
            ['cm project create <name>', 'Create new project'],
            ['cm project use <name>', 'Switch current project'],
            ['cm project list', 'View project list']
          ]
        },
        {
          title: '🌍 Environment Management',
          commands: [
            ['cm env list', 'List all environments'],
            ['cm env create <env>', 'Create environment'],
            ['cm env use <env>', 'Switch default environment']
          ]
        },
        {
          title: '📦 Module Management',
          commands: [
            ['cm add <module>[@version]', 'Install module'],
            ['cm remove <module>', 'Remove module'],
            ['cm list', 'View installed modules'],
            ['cm info <module>', 'View module information'],
            ['cm upgrade <module>', 'Upgrade module'],
            ['cm search <keyword>', 'Search module marketplace']
          ]
        },
        {
          title: '🔑 Secrets & Configuration',
          commands: [
            ['cm secret list', 'View environment secrets'],
            ['cm secret set KEY=VALUE', 'Set secret'],
            ['cm secret delete KEY', 'Delete secret'],
            ['cm bind <file.yaml>', 'Batch bind configuration']
          ]
        },
        {
          title: '😠 Debugging & Calling',
          commands: [
            ['cm call <action> --input <json>', 'Call module method'],
            ['cm logs <module>', 'View module logs'],
            ['cm doctor', 'Check project health']
          ]
        },
        {
          title: '📦 Module Development',
          commands: [
            ['cm create module <name>', 'Create new module'],
            ['cm build', 'Build and check module'],
            ['cm link', 'Link local module'],
            ['cm unlink', 'Remove local link']
          ]
        },
        {
          title: '🚀 Publishing & Versions',
          commands: [
            ['cm version [patch|minor|major]', 'Bump version'],
            ['cm publish [--tag <tag>]', 'Publish module version'],
            ['cm promote --from <tag> --to <tag>', 'Promote version'],
            ['cm history <module>', 'View version history']
          ]
        },
        {
          title: '🤝 Collaboration',
          commands: [
            ['cm share <project|module>', 'Share resource'],
            ['cm fork <project>', 'Fork project'],
            ['cm clone <url>', 'Import from share link']
          ]
        },
        {
          title: '🔧 CLI Configuration',
          commands: [
            ['cm config list', 'View CLI configuration'],
            ['cm config set KEY=VALUE', 'Modify CLI configuration'],
            ['cm version', 'View CLI version']
          ]
        }
      ];

      sections.forEach(section => {
        logger.log(`${section.title}`);
        const headers = ['Command', 'Description'];
        const rows = section.commands.map(([cmd, desc]) => [cmd, desc]);
        logger.log(createTable(headers, rows));
        logger.log('');
      });

      logger.info('For detailed help on a specific command, use: cm help <command>');
      logger.info('Documentation: https://docs.cmodel.io');
    });
}